<template>
	<view class="container">
		<view class="header-wrap">
			<text class="title">活动列表</text>
			<view class="filter" @click="onOpenSearch()">
				<uni-icons type="settings" size="24"></uni-icons>
				<text>筛选</text>
			</view>
		</view>

		<view class="content-wrap">
			<view class="item" v-for="item in activityList">
				<view class="no">
					<text> 活动编号：</text>
					<text selectable="true" class="noN">{{ item.activityNo }}</text>
				</view>
				<view class="line"></view>
				<text class="title">{{ item.activityName }}{{ item.couponList?.length > 1 ? '（卡包）' : '' }}</text>
				<view class="number">
					<text>已派发：{{ couponCom(item.couponList) }}张</text>
				</view>
				<view class="number">
					<text>本机构总：{{ couponNum(item.couponList) }}张</text>
					<text class="price">¥ {{ couponPrice(item.couponList) }}</text>
				</view>
				<view class="number">
					<text>已分配下级：{{ couponGet(item.couponList) }}张</text>
					<text>券面额</text>
				</view>
				<view class="number">
					<!-- <view class="qrcode" @click="onOpenGenerateQr(item)">生成二维码</view> -->
					<view class="info" @click="onDetail(item.activityId,(couponNum(item.couponList)) || 0)">查看派券记录
					</view>

					<view class="history" @click="onHistory(item.activityId)">
						<uni-icons type="calendar" color="white" size="26"></uni-icons>
						<text>生成记录</text>
					</view>
				</view>
			</view>
			<gzListNull :list="activityList"></gzListNull>
		</view>

		<!-- 搜索弹窗 -->
		<uni-popup ref="searchPopup" type="top">
			<view class="popup-search">
				<view class="item">
					<text>活动编号</text>
					<input class="input" placeholder-style="color:#BBBBBB" placeholder="请输入活动编号" v-model="vdata.queryParams.activityNo" />
				</view>
				<view class="item">
					<text>活动名称</text>
					<input class="input" placeholder-style="color:#BBBBBB" placeholder="请输入活动名称" v-model="vdata.queryParams.activityName" />
				</view>
				<view class="item">
					<text>活动时间</text>
					<view class="time-wrap">
						<view class="time" @click="onOpenDate(true)">
							<text :style="vdata.queryParams.startTime?'':'color:#BBBBBB'">{{vdata.queryParams.startTime?vdata.queryParams.startTime:'开始时间'}}</text>
							<uni-icons type="down" color="#A0A9C0" size="20"></uni-icons>
						</view>
						<text class="to">至</text>
						<view :style="vdata.queryParams.endTime?'':'color:#BBBBBB'" class="time" @click="onOpenDate(false)">
							<text>{{vdata.queryParams.endTime?vdata.queryParams.endTime:'结束时间'}}</text>
							<uni-icons type="down" color="#A0A9C0" size="20"></uni-icons>
						</view>
					</view>
				</view>
				<view class="bottom-wrap">
					<text class="reset" @click="onReset">重置</text>
					<text class="query" @click="onQuery">查询</text>
				</view>
			</view>
		</uni-popup>

		<!-- 生成二维码弹窗 -->
		<uni-popup ref="generateQrPopup" type="bottom">
			<view class="popup-generate-qr">
				<text class="title">领券二维码生成</text>
				<uni-icons type="closeempty" size="24" color="darkgray" class="close" @click="onCloseGenerateQr()"></uni-icons>
				<view class="line"></view>
				<view class="number">
					<text>本活动还可发放：</text>
					<view>
						<text v-if="vdata.currentRecord.couponList" class="price">{{ couponNum(vdata.currentRecord.couponList) }}</text>次
					</view>
				</view>
				<text style="padding-top: 15rpx">生成二维码类型:</text>
				<radio-group @change="radioChange">
					<label class="radio-label">
						<radio :value="0" :checked="true" style="transform:scale(0.7)" />
						<view style="padding: 5rpx 0">无限次使用二维码</view>
					</label>
					<label class="radio-label">
						<radio :value="1" style="transform:scale(0.7)" />
						<view class="content">
							<view class="number">单客户可领取 <input class="input" v-model="vdata.generateQrParams.numEveryone" /> 次</view>
							<view class="number">总共可领取 <input class="input" v-model="vdata.generateQrParams.numTotal" /> 次二维码</view>
						</view>
					</label>
				</radio-group>
				<text style="padding-top: 15rpx"> <text style="color: red;">*</text> 数量为-1或不填写，则为不限制发放数量，总次数需要大于等
					于单客户领用次数</text>
				<text class="bottom-wrap" @click="onOpenQr(vdata.currentRecord)">
					生成二维码
				</text>
			</view>
		</uni-popup>

		<!-- 二维码弹窗 -->
		<uni-popup ref="qrPopup" type="bottom">
			<view class="popup-qr">
				<text class="title">领券二维码</text>
				<uni-icons type="closeempty" size="24" color="darkgray" class="close" @click="onCloseQr()"></uni-icons>
				<view class="line"></view>
				<image v-if="vdata.qrImage" mode="widthFix" :src="vdata.qrImage"></image>
				<text class="bottom-wrap" @click="saveQRcode()">
					保存二维码
				</text>
			</view>
		</uni-popup>

		<!-- 日历 -->
		<uni-calendar ref="calendarRef" :insert="false" @confirm="onConfirmDate" />
	</view>
</template>

<script setup>
	import { reactive, ref, computed, getCurrentInstance } from 'vue'
	import { $sendToMchUserActivity, $saveQrcode, $getQrcode } from '@/http/marketing/apiMarketing.js'
	import useGetList from '@/hooks/useGetList.js'
	import storageManage from '@/util/storageManage.js'
	import numberUtil from '@/util/numberUtil.js'
	import { onShow, onLoad } from '@dcloudio/uni-app'

	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	// const { useDataResult, getList } = useGetList($sendToMchUserActivity, data => data, { agentNo: storageManage.userInfo().khjlAgentNo, templateNo: "ACTE004" })
	// 搜索弹窗
	const searchPopup = ref();

	// 搜索弹窗
	const calendarRef = ref();

	// 生成二维码弹窗
	const generateQrPopup = ref();

	// 二维码弹窗
	const qrPopup = ref();


	const vdata = reactive({
		queryParams: {
			activityNo: '',
			activityName: '',
			startTime: '',
			endTime: ''
		},
		isStartDate: true,
		generateQrParams: {
			type: 0,
			numEveryone: '',
			numTotal: '',
		},
		qrImage: '',
		currentRecord: {}, // 当前记录 即要生成二维码的活动
	})

	// 获取列表数据
	const activityList = ref([])

	onLoad(() => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		$sendToMchUserActivity({
			agentNo: storageManage.userInfo().khjlAgentNo,
			templateNo: "ACTE004"
		}).then(res => {
			uni.hideLoading()
			activityList.value = res.bizData
		})
	})


	// 生成的二维码 跳转的营销小程序路径
	const PATH_URL = 'pages/welcome/index'

	// 卡券面额
	const couponPrice = computed(() => {
		return (couponList) => {
			if (couponList && couponList.length) {
				return numberUtil.getFloatNumber(couponList.reduce((accumulator, currentValue) => accumulator +
					currentValue.couponPrice, 0) / 100, 2)
			} else {
				return 0
			}
		}
	})
// 卡券已派发数量
const couponGet = computed(() => {
    return (couponList) => {
        if (couponList && couponList.length) {
            return couponList.reduce((accumulator, currentItem) => {
                return accumulator + (currentItem.numAllocation || '--');
            }, '');
        } else {
            return 0;
        }
    };
});

// 卡券已派发数量
const couponCom = computed(() => {
    return (couponList) => {
        if (couponList && couponList.length) {
            return couponList.reduce((accumulator, currentItem) => {
                return accumulator + (currentItem.numConsume || '--');
            }, '');
        } else {
            return 0;
        }
    };
});

// 卡券还可派发数量
const couponNum = computed(() => {
    return (couponList) => {
        if (couponList && couponList.length) {
            return couponList.reduce((accumulator, currentItem) => {
                return accumulator + (currentItem.num || '--');
            }, '');
        } else {
            return 0;
        }
    };
});


	/**
	 * 打开搜索弹窗
	 */
	const onOpenSearch = () => {
		searchPopup.value.open();

	}
	/**
	 * 筛选
	 */
	const onQuery = () => {
		getList(vdata.queryParams)
		onCloseSearch()
	}
	/**
	 * 重置
	 */
	const onReset = () => {
		vdata.queryParams = {
			activityNo: '',
			activityName: '',
			startTime: '',
			endTime: ''
		}
	}

	/**
	 *  详情
	 */
	const onDetail = (activityId, remainNum) => {
		getApp().preventActive(() => {
			uni.navigateTo({
				url: '/marketing/coupon/detail?activityId=' + activityId + '&remainNum=' + remainNum
			})
		})
	}

	/**
	 * 关闭搜索弹窗
	 */
	const onCloseSearch = () => {
		searchPopup.value.close();
	}

	/**
	 * 打开日历
	 */
	const onOpenDate = (isStartDate) => {
		vdata.isStartDate = isStartDate
		calendarRef.value.open();
	}

	/**
	 * 打开生成二维码弹窗
	 */
	const onOpenGenerateQr = (record) => {
		vdata.currentRecord = JSON.parse(JSON.stringify(record))
		generateQrPopup.value.open();
	}

	/**
	 * 关闭生成二维码弹窗
	 */
	const onCloseGenerateQr = () => {
		generateQrPopup.value.close();
	}

	/**
	 * radio选择事件
	 */
	const radioChange = (event) => {
		if (event.detail) {
			vdata.generateQrParams.type = event.detail.value
		}
	}

	/**
	 * 生成二维码 关闭二维码配置弹窗 打开生成的二维码弹窗
	 */
	const onOpenQr = async (record) => {
		uni.showLoading({
			title: '生成中...'
		})
		onCloseGenerateQr();
		let numConsume = 0
		if (record.couponList[0].couponGet) {
			numConsume = record.couponList[0].couponGet
		}
		const uploadData = {
			numConsume,
			activityId: record.activityId,
			pathUrl: PATH_URL
		}
		if (vdata.generateQrParams.type == 0) {
			uploadData.type = 0
		} else {
			uploadData.type = 1
			uploadData.numEveryone = vdata.generateQrParams.numEveryone
			uploadData.numTotal = vdata.generateQrParams.numTotal
		}

		$saveQrcode(uploadData).then(({
			bizData
		}) => {
			$getQrcode({
				qrcodeRecordId: bizData
			}).then(({
				bizData
			}) => {
				uni.hideLoading()
				$infoBox.successToast('生成成功')
				vdata.qrImage = 'data:image/png;base64,' + bizData
				qrPopup.value.open()
			})
		})

	}

	/**
	 * 关闭二维码弹窗
	 */
	const onCloseQr = () => {
		qrPopup.value.close();
	}

	// 将base64 图片保存到本地系统相册
	function saveQRcode() {
		var writeContent = vdata.qrImage.replace('data:image/png;base64,', '')
		var fs = uni.getFileSystemManager();
		var fileName = 'IMG_' + new Date().getTime() + '.jpg'
		fs.writeFile({
			filePath: uni.env.USER_DATA_PATH + '/' + fileName,
			data: writeContent,
			encoding: 'base64',
			success: res => {
				uni.saveImageToPhotosAlbum({
					filePath: uni.env.USER_DATA_PATH + '/' + fileName,
					success: function(res) {
						$infoBox.toast('保存成功')
						onCloseQr()
					},
					fail: function(err) {
						// console.log(err)
					}
				})
				// console.log(res)
			},
			fail: err => {
				// console.log(err)
			}
		})
	}

	/**
	 * 日期选择
	 */
	const onConfirmDate = (result) => {
		if (vdata.isStartDate) {
			vdata.queryParams.startTime = result.fulldate
		} else {
			vdata.queryParams.endTime = result.fulldate
		}
	}

	/**
	 * 历史记录
	 */
	const onHistory = (activityId) => {
		uni.navigateTo({
			url: `/marketing/coupon/qrcodeRecord?activityId=${activityId}`
		})
	}
</script>

<style lang="less">
	@page-backgroud: #F6F7FC; //页面背景色

	page {
		background: @page-backgroud;
	}

	.container {
		min-height: calc(100vh - 60rpx);
		margin: 30rpx 20rpx 30rpx 20rpx;
		overflow: hidden;

		.header-wrap {
			width: 100%;
			position: fixed;
			height: 120rpx;
			top: 0;
			left: 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			z-index: 2;
			box-sizing: border-box;
			padding: 0 30rpx;
			background-color: @page-backgroud;

			.title {
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				font-style: normal;
				flex-grow: 1;
			}


			.filter {
				display: flex;
				align-items: center;
				border-radius: 40rpx;
				background-color: white;
				padding: 8rpx 20rpx;
				border: 1rpx solid #C8C8C8;

				text {
					font-size: 26rpx;
					color: black;
					letter-spacing: 1px;
					margin-bottom: 2rpx;
				}
			}
		}

		.content-wrap {
			width: 100%;
			margin-top: 100rpx;
			position: relative;
			z-index: 0;

			.item {
				box-sizing: border-box;
				padding: 30rpx;
				background: #fff;
				border-radius: 20rpx;
				box-shadow: 0rpx -10rpx 30rpx -30rpx rgba(0, 0, 0, 0.8);
				display: flex;
				flex-direction: column;
				margin-bottom: 30rpx;


				.no {
					display: flex;
					font-size: 26rpx;
					color: #999999;

					.noN {
						color: #24C789;
					}

				}

				.line {
					height: 1rpx;
					background-color: #E6E6E6;
					margin: 20rpx 0rpx;
				}

				.title {
					font-weight: bold;
					font-size: 32rpx;
					color: #333333;
					margin: 15rpx 0rpx;
				}

				.number {
					display: flex;
					align-items: center;
					justify-content: space-between;
					color: darkgray;
					font-size: 26rpx;
					margin: 5rpx 0rpx;

					.info {
						margin-top: 30rpx;
						border: 1rpx solid #C8C8C8;
						border-radius: 35rpx;
						background-color: white;
						padding: 15rpx 30rpx;
						color: #333333;
						box-shadow: 0rpx -10rpx 30rpx -30rpx rgba(0, 0, 0, 0.8);
					}

					.price {
						font-size: 38rpx;
						color: #FF8833;
						font-weight: bold;
					}

					.qrcode {
						border: 1rpx solid #C8C8C8;
						border-radius: 35rpx;
						background-color: white;
						padding: 15rpx 30rpx;
						color: #333333;
						margin-top: 30rpx;
						box-shadow: 0rpx -10rpx 30rpx -30rpx rgba(0, 0, 0, 0.8);
					}

					.history {
						display: flex;
						align-items: center;
						border-radius: 40rpx;
						background-color: #24C789;
						padding: 8rpx 20rpx;
						margin-top: 30rpx;

						text {
							font-size: 26rpx;
							color: #FFFFFF;
							letter-spacing: 1px;
							margin-bottom: 1rpx;
						}
					}
				}

			}
		}

		.popup-search {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 30rpx;
			font-size: 26rpx;
			background-color: white;
			border-radius: 0 0 20rpx 20rpx;
			letter-spacing: 1px;
			box-sizing: border-box;
			margin-top: 120rpx;

			.item {
				display: flex;
				flex-direction: column;
				font-size: 28rpx;
				margin-bottom: 30rpx;
				width: 100%;

				.input {
					border-radius: 40rpx;
					padding: 18rpx 30rpx;
					background-color: #F6F7FC;
					margin-top: 20rpx;
					font-size: 30rpx;
				}

				.time-wrap {
					display: flex;
					flex-direction: row;
					align-items: center;
					margin-top: 20rpx;

					.time {
						border-radius: 40rpx;
						padding: 18rpx 30rpx;
						background-color: #F6F7FC;
						font-size: 30rpx;
						flex-grow: 1;
						display: flex;
						justify-content: space-between;
					}

					.to {
						margin: 0 20rpx;
					}
				}

			}


			.bottom-wrap {
				display: flex;
				flex-direction: row;
				align-items: center;
				font-size: 30rpx;
				margin-top: 30rpx;
				margin-bottom: 10rpx;
				width: 100%;

				.reset {
					color: black;
					border-radius: 40rpx;
					width: 25%;
					padding: 18rpx 0rpx;
					background-color: #F4F5F5;
					text-align: center;
					margin-right: 30rpx;
				}

				.query {
					color: white;
					border-radius: 40rpx;
					width: 75%;
					padding: 18rpx 0rpx;
					background-color: #24C789;
					margin-top: 30rpx;
					text-align: center;
					margin-bottom: 10rpx;
				}
			}

		}

		.popup-generate-qr {
			display: flex;
			flex-direction: column;
			padding: 40rpx 30rpx;
			font-size: 28rpx;
			background-color: white;
			border-radius: 20rpx 20rpx 0 0;
			letter-spacing: 1px;
			box-sizing: border-box;
			position: relative;

			.title {
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 20rpx;
				text-align: center;
			}

			.close {
				position: fixed;
				right: 0;
				top: 0;
				margin-top: 25rpx;
				margin-right: 25rpx;
			}

			.line {
				height: 1rpx;
				background-color: #E6E6E6;
				margin: 20rpx 0rpx;
			}

			.number {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 30rpx;

				.price {
					font-size: 38rpx;
					color: #FF8833;
					font-weight: bold;
				}
			}

			.radio-label {
				display: flex;
				font-size: 28rpx;
				margin-top: 20rpx;
				align-items: center;
				border-radius: 15rpx;
				background-color: white;
				padding: 20rpx 30rpx;
				border: 1rpx solid #D7D7D7;

				.content {
					display: flex;
					flex-direction: column;

					.number {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						margin: 0;
						padding: 5rpx 0;

						input {
							border-radius: 40rpx;
							padding: 13rpx 40rpx;
							background-color: #F6F7FC;
							font-size: 30rpx;
							width: 80rpx;
							margin: 0 10rpx;
						}
					}
				}
			}

			.bottom-wrap {
				font-size: 30rpx;
				width: 100%;
				color: white;
				border-radius: 40rpx;
				padding: 20rpx 0rpx;
				background-color: #24C789;
				margin-top: 40rpx;
				text-align: center;
				margin-bottom: 10rpx;
			}

		}

		.popup-qr {
			display: flex;
			flex-direction: column;
			padding: 40rpx 30rpx;
			font-size: 28rpx;
			background-color: white;
			border-radius: 20rpx 20rpx 0 0;
			letter-spacing: 1px;
			box-sizing: border-box;
			align-items: center;
			position: relative;

			.title {
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 20rpx;
				text-align: center;
			}

			.close {
				position: fixed;
				right: 0;
				top: 0;
				margin-top: 25rpx;
				margin-right: 25rpx;
			}

			.line {
				height: 1rpx;
				background-color: #E6E6E6;
				margin: 20rpx 0rpx;
				width: 100%;
			}

			image {
				width: 70%;
				// border: 10rpx solid #24C78933;
				padding: 10rpx;
				margin: 50rpx 0rpx;
			}

			.bottom-wrap {
				font-size: 30rpx;
				width: 100%;
				color: white;
				border-radius: 40rpx;
				padding: 20rpx 0rpx;
				background-color: #24C789;
				text-align: center;
				margin-bottom: 10rpx;
			}

		}
	}
</style>